package com.gery.tn.ui.search;

import com.gery.tn.backend.model.Client;
import com.gery.tn.backend.service.DAOFactory;
import com.gery.tn.ui.MainWindow;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.DefaultEditorKit;




public class SearchPanel extends JPanel {

    private ImageIcon img;
    private JTextField textField;
    private MainWindow myParent;
    
    
    public SearchPanel(MainWindow parent) {
        this.setLayout(new GridLayout(1, 1));
        this.setPreferredSize(new Dimension(554, 35));
        this.setBorder(null);
        myParent = parent;
                        
        textField = new JTextField();
        
        textField.setBorder(null);
        textField.setPreferredSize(this.getSize());
        textField.setFont(new Font("Apple", Font.BOLD, 14));
        textField.setOpaque(false);
        (textField.getActionMap().get(DefaultEditorKit.beepAction)).setEnabled(false);
        
        img = new ImageIcon(this.getClass().getClassLoader().getResource("com/gery/tn/ui/images/searchBar.png"));
        this.add(textField);
        
        
        //--- Search Logic
        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) myParent.getResultList().fastAppointment();
                if (textField.getText().length() == 0) myParent.getResultList().clearList();
                else {
                    List<Client> results = DAOFactory.getInstance().getClientService().searchFor(textField.getText());
                    myParent.getResultList().setList(results);
                }
            }
        });
        textField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                clearTextField();
                myParent.getResultList().clearList();
            }
        });
        
    }
    
    public void clearTextField() {
        textField.setText("");
    }
    
    
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);      
        g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), this);
    }
    
}
